package org.karelun.rabbit.rcp.action;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.emf.cdo.net4j.CDONet4jSession;
import org.eclipse.emf.cdo.net4j.CDONet4jSessionConfiguration;
import org.eclipse.emf.cdo.net4j.CDONet4jUtil;
import org.eclipse.emf.cdo.view.CDOAdapterPolicy;
import org.eclipse.emf.cdo.view.CDOView;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.net4j.Net4jUtil;
import org.eclipse.net4j.connector.IConnector;
import org.eclipse.net4j.util.container.IPluginContainer;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.karelun.rabbit.graph.GraphPackage;
import org.karelun.rabbit.rcp.editor.RabbitEditorInput;

public class OpenViewHandler extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		IWorkbenchPage page =PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
		
		String server = "localhost";//"192.168.31.129";
		String respository = "rabbit";

		IConnector connector = Net4jUtil.getConnector(IPluginContainer.INSTANCE, "tcp", server);
		CDONet4jSessionConfiguration config = CDONet4jUtil.createNet4jSessionConfiguration();
		config.setConnector(connector);
		config.setRepositoryName(respository);

		CDONet4jSession session = config.openNet4jSession();
		session.getPackageRegistry().putEPackage(GraphPackage.eINSTANCE);
		CDOView cdoView=openView(session);
		cdoView.options().addChangeSubscriptionPolicy(CDOAdapterPolicy.ALL);
		
		openEditor(page, cdoView);
		return null;
	}
	
	protected String getResourcePathName(){
		return "/rsdj";
	}
	
	protected CDOView openView(CDONet4jSession session){
		return session.openTransaction();
	}
	
	protected void openEditor(IWorkbenchPage page, CDOView cdoView){
		String resourcePath = getResourcePathName();
		if(!cdoView.hasResource(resourcePath)){
			MessageDialog.openInformation(null, "", "No resource path: "+resourcePath);
			return;
		}
		try {
			String path = cdoView.getResource(resourcePath).getPath();
			 RabbitEditorInput editorInput = new RabbitEditorInput(cdoView, path);
			 page.openEditor(editorInput, "org.karelun.rabbit.editor");
		 } catch (PartInitException e) {
			 e.printStackTrace();
		 }
	}
}
